package com.qinggeng.project.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.qinggeng.common.enums.CommonEnum;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.utils.SecurityUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.common.utils.poi.ExcelUtil;
import com.qinggeng.framework.aspectj.lang.annotation.Log;
import com.qinggeng.framework.aspectj.lang.enums.BusinessType;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.framework.web.page.TableDataInfo;
import com.qinggeng.project.api.dto.ActivityGoodsDto;
import com.qinggeng.project.system.domain.AttrRow;
import com.qinggeng.project.system.domain.Goods;
import com.qinggeng.project.system.dto.GoodsImgDTO;
import com.qinggeng.project.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 商品信息Controller
 *
 * @author qinggeng
 * @date 2020-06-15
 */
@Slf4j
@RestController
@RequestMapping("/system/goods")
public class GoodsController extends BaseController {
    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private  IGoodsKeepService goodsKeepService;

    @Autowired
    private IGoodsKeywordsService keywordsService;

    @Autowired
    private IGoodsActiviyService goodsActiviyService;

    @Autowired
    private GoodsImgService goodsImgService;

    @Autowired
    private IAssistRecordService assistRecordService;

    @Autowired
    private IGoodsPercentService goodsPercentService;


    /**
     * 查询商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/list")
    public TableDataInfo list(Goods goods) {
        goods.setDelFalg("10");
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())) {
            goods.setShopId(SecurityUtils.getShopId());
        }
        startPage();
        List<Goods> goodsSkuVoList = goodsService.systemSelectGoodsList(goods);
        return getDataTable(goodsSkuVoList);
    }

    /**
     * 查询库存小于30商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/listLittleGoods")
    public TableDataInfo listLittleGoods(Goods goods) {
        //List<Goods> list = goodsService.selectGoodsList(goods);
        goods.setDelFalg("10");
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            goods.setShopId(SecurityUtils.getShopId());
        }
        startPage();
        List<Goods> goodsSkuVoList = goodsService.selectLittleGoodsListForOne(goods);
        return getDataTable(goodsSkuVoList);
    }

    /**
     * 导出商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:goods:export')")
    @Log(title = "商品信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Goods goods) {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        return util.exportExcel(list, "goods");
    }

    /**
     * 获取商品信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:query')")
    @GetMapping(value = "/{goodsId}")
    public AjaxResult getInfo(@PathVariable("goodsId") Long goodsId) {
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            Goods goods1 = goodsService.selectGoodsById(goodsId);
            if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())){
                return AjaxResult.error("只能操作自己所属商品");
            }

        }
        Goods goods = goodsService.selectGoodsByIdYg(goodsId);

        ActivityGoodsDto activityGoodsDto = null;
        if (goods.getGoodsType().equals("40")){
            activityGoodsDto = goodsActiviyService.selectGooodsActivityDtoBy(goodsId);
        }

        AttrRow attrRow = new AttrRow();
        attrRow.setAttributes(goods.getAttributes());
        attrRow.setGoodsPrice(goods.getGoodsPrice());
        attrRow.setGroupPrice(goods.getGroupPrice());
        attrRow.setLinePrice(goods.getLinePrice());
        attrRow.setBuyPrice(goods.getBuyPrice());
        attrRow.setGoodsName(goods.getGoodsName());
        attrRow.setGoodsImg(goods.getGoodsImg());
        attrRow.setLimitNum(goods.getLimitNum());
        attrRow.setVipPrice(goods.getVipPrice());
        if (goods.getGoodsType().equals("40") && activityGoodsDto != null){
            attrRow.setGroupNum(activityGoodsDto.getGroupNum());
        }
        attrRow.setGoodsLongImgs(goodsImgService.getSysLongImages(goodsId));
        attrRow.setGoodsMainImgs(goodsImgService.getSysMainImages(goodsId));
        if (goods.getGoodsType().equals("40")){
            if (activityGoodsDto != null){
                attrRow.setGroupNum(activityGoodsDto.getGroupNum());
            }
        }
        List<AttrRow> attrRows = new ArrayList<>();
        attrRows.add(attrRow);
        goods.setAttrRows(attrRows);
        return AjaxResult.success(goods);
    }

    /**
     * 新增商品信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:add')")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody Goods goods) {
        List<AttrRow> attrRows = JSONArray.parseArray(JSON.toJSONString(goods.getAttrRows()), AttrRow.class);
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            goods.setShopId(SecurityUtils.getShopId());
            goods.setAddType(CommonEnum.STATUS_20.getValue());
        }
        Long mainCategory =  goodsService.selectMaxGoodsId();

        if (mainCategory == null){

            mainCategory = 1L;
        }else {
            mainCategory +=1;
        }
        Goods goods1 = null;
        for (AttrRow attrRow : attrRows) {
            goods1 = new Goods();
            BeanUtils.copyProperties(goods,goods1);
            goods1.setAttributes(attrRow.getAttributes());
            goods1.setMainCategory(mainCategory);
            goods1.setGoodsPrice(attrRow.getGoodsPrice());
            goods1.setGroupPrice(attrRow.getGroupPrice());
            goods1.setBuyPrice(attrRow.getBuyPrice());
            goods1.setLinePrice(attrRow.getLinePrice());
            goods1.setAttributesName("规格");
            goods1.setGoodsName(attrRow.getGoodsName());
            goods1.setGoodsImg(attrRow.getGoodsImg());
            goods1.setGoodsLongImg(attrRow.getGoodsLongImg());
            goods1.setLimitNum(attrRow.getLimitNum());


            int i = goodsService.insertGoods(goods1);
            if (i<=0){
                return AjaxResult.error("新增商品失败");
            }

            GoodsImgDTO goodsImgDTO=new GoodsImgDTO();
            goodsImgDTO.setGoodsId(goods1.getGoodsId());

             String m= attrRow.getGoodsMainImgs();
             if (StringUtils.isEmpty(m)){
                 return AjaxResult.error("主图不能为传空");
             }
            //添加多张商品主图
            String[] mainImgs=m.split(",");
            goodsImgDTO.setGoodsMainImgs(Arrays.asList(mainImgs));

            String d=goods.getListImg();
            if (StringUtils.isEmpty(m)){
                return AjaxResult.error("详图不能为传空");
            }
            //添加多张商品详情
            String[] detailsImgs=d.split(",");
            goodsImgDTO.setGoodstDetailsImgs(Arrays.asList(detailsImgs));

            //添加长图
            String longImg= attrRow.getGoodsLongImgs();
            if (StringUtils.isEmpty(longImg)){
                return AjaxResult.error("长图不能为传空");
            }
            String[] longImgs=longImg.split(",");

            goodsImgDTO.setGoodstLongImgs(Arrays.asList(longImgs));

            goodsImgService.insertGoodsImgs(goodsImgDTO);

            goodsService.updateGoodsPercentage(goods1);

        }

        return AjaxResult.success("新增商品成功",goods1);
    }

    /**
     * 修改商品信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:edit')")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Goods goods) {

            if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
                Goods goods1 = goodsService.selectGoodsById(goods.getGoodsId());
                if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())){
                    return AjaxResult.error("只能操作自己所属商品");
                }
            }
            List<AttrRow> attrRows = JSONArray.parseArray(JSON.toJSONString(goods.getAttrRows()), AttrRow.class);

            if (attrRows.size()>1){
                //删除当前sku
                Long goodsId=goods.getGoodsId();
                goodsService.deleteGoodsById(goodsId);
                goodsImgService.deleteImages(goodsId);
                Goods goods1 = null;
                for (AttrRow attrRow : attrRows) {
                    goods1 = new Goods();
                    BeanUtils.copyProperties(goods,goods1);
                    goods1.setGoodsId(null);
                    goods1.setAttributes(attrRow.getAttributes());
                    goods1.setGoodsPrice(attrRow.getGoodsPrice());
                    goods1.setGroupPrice(attrRow.getGroupPrice());
                    goods1.setBuyPrice(attrRow.getBuyPrice());
                    goods1.setAttributesName("规格");
                    goods1.setLinePrice(attrRow.getLinePrice());
                    goods1.setGoodsName(attrRow.getGoodsName());
                    goods1.setGoodsImg(attrRow.getGoodsImg());
                    goods1.setGoodsLongImg(attrRow.getGoodsLongImg());
                    goods1.setLimitNum(attrRow.getLimitNum());
                    goods1.setVipPrice(attrRow.getVipPrice());
                    int i = goodsService.insertGoods(goods1);
                    if (i<=0){
                        return AjaxResult.error("新增商品失败");
                    }

                    GoodsImgDTO goodsImgDTO=new GoodsImgDTO();
                    goodsImgDTO.setGoodsId(goods1.getGoodsId());
                    String m= attrRow.getGoodsMainImgs();
                    if (StringUtils.isEmpty(m)){
                        return AjaxResult.error("主图不能为传空");
                    }
                    //添加多张商品主图
                    String[] mainImgs=m.split(",");
                    goodsImgDTO.setGoodsMainImgs(Arrays.asList(mainImgs));

                    String d=goods.getListImg();
                    if (StringUtils.isEmpty(m)){
                        return AjaxResult.error("详图图不能为传空");
                    }
                    //添加多张商品详情
                    String[] detailsImgs=d.split(",");
                    goodsImgDTO.setGoodstDetailsImgs(Arrays.asList(detailsImgs));
                    //添加长图
                    String longImg= attrRow.getGoodsLongImgs();
                    if (StringUtils.isEmpty(longImg)){
                        return AjaxResult.error("长图不能为传空");
                    }
                    String[] longImgs=longImg.split(",");
                    goodsImgDTO.setGoodstLongImgs(Arrays.asList(longImgs));
                    goodsImgService.insertGoodsImgs(goodsImgDTO);

                    goodsService.updateGoodsPercentage(goods);

                }
                return AjaxResult.success("新增成功");
            }
            if (attrRows.size()==1){
                AttrRow attrRow=attrRows.get(0);
                goods.setAttributes(attrRow.getAttributes());
                goods.setGoodsPrice(attrRow.getGoodsPrice());
                goods.setGroupPrice(attrRow.getGroupPrice());
                goods.setLinePrice(attrRow.getLinePrice());
                goods.setBuyPrice(attrRow.getBuyPrice());
                goods.setGoodsName(attrRow.getGoodsName());
                goods.setGoodsImg(attrRow.getGoodsImg());
                goods.setGoodsLongImg(attrRow.getGoodsLongImg());
                goods.setLimitNum(attrRow.getLimitNum());
                goods.setVipPrice(attrRow.getVipPrice());
                goodsImgService.deleteImages(goods.getGoodsId());
                GoodsImgDTO goodsImgDTO=new GoodsImgDTO();
                goodsImgDTO.setGoodsId(goods.getGoodsId());

                String m= attrRow.getGoodsMainImgs();
                if (StringUtils.isEmpty(m)){
                    return AjaxResult.error("主图不能为传空");
                }
                //添加多张商品主图
                String[] mainImgs=m.split(",");
                goodsImgDTO.setGoodsMainImgs(Arrays.asList(mainImgs));

                String d=goods.getListImg();
                if (StringUtils.isEmpty(m)){
                    return AjaxResult.error("详图图不能为传空");
                }
                //添加多张商品详情
                String[] detailsImgs=d.split(",");
                goodsImgDTO.setGoodstDetailsImgs(Arrays.asList(detailsImgs));
                //添加长图
                String longImg= attrRow.getGoodsLongImgs();
                if (StringUtils.isEmpty(longImg)){
                    return AjaxResult.error("长图不能为传空");
                }
                String[] longImgs=longImg.split(",");
                goodsImgDTO.setGoodstLongImgs(Arrays.asList(longImgs));
                goodsImgService.insertGoodsImgs(goodsImgDTO);

                int rows=goodsService.updateGoods(goods);
                if(rows<1){
                    return AjaxResult.error("修改失败");
                }
                goodsService.updateGoodsPercentage(goods);
                return AjaxResult.success("修改商品成功");
            }
            return AjaxResult.error("无Sku请重试");
    }

    /**
     * 删除商品信息
     */
    @PreAuthorize("@ss.hasPermi('system:goods:remove')")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{goodsIds}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable Long[] goodsIds) {
        // 进行逻辑批量删除
        for (Long goodsId : goodsIds) {
            if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
                Goods goods1 = goodsService.selectGoodsById(goodsId);
                if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())){
                    return AjaxResult.error("只能操作自己所属商品");
                }
            }
        }
        return toAjax(goodsService.logicalDeleteGoodsByIds(goodsIds));
    }

    @PostMapping("/changeState")
    @ResponseBody
    public AjaxResult changeState(@RequestBody Goods goods) {
        if (goods.getStatus().equals("10")){
            goods.setStatus("20");
        }else{
            goods.setStatus("10");
        }
        if (SecurityUtils.getLoginUser().getUser().getUserType().equals(UserTypeEnum.SHOP.getCode())){
            Goods goods1 = goodsService.selectGoodsById(goods.getGoodsId());
            if (goods1.getShopId() == null || !goods1.getShopId().equals(SecurityUtils.getShopId())){
                return AjaxResult.error("只能操作自己所属商品");
            }
        }
        return toAjax(goodsService.updateGoods(goods));
    }

    @PreAuthorize("@ss.hasPermi('system:goods:keep')")
    @GetMapping(value = "/keep/{goodsId}")
    public AjaxResult  getKeep(@PathVariable("goodsId") Long goodsId){
        if (SecurityUtils.getShopId() == null){
            return AjaxResult.error("店铺不存在");
        }
        return AjaxResult.success(goodsKeepService.selectGoodsKeepByGoodsId(goodsId,SecurityUtils.getShopId()));
    }

    @PreAuthorize("@ss.hasPermi('system:goods:edit')")
    @GetMapping(value = "/relieve")
    public AjaxResult  relieve( Long goodsId){

        return AjaxResult.success(goodsService.relieve(goodsId));
    }

    @PreAuthorize("@ss.hasPermi('system:goods:edit')")
    @PostMapping(value = "/establish")
    public AjaxResult  establish(Long goodsId, Long wholeGoodsId){
        log.info("goodsId:"+goodsId);
        log.info("wholeGoodsId:"+wholeGoodsId);
        return AjaxResult.success(goodsService.establish(goodsId,wholeGoodsId));
    }
}
